package cn.qiyu5522.tk_ems.stpinterface;

import cn.dev33.satoken.stp.StpInterface;
import cn.qiyu5522.tk_ems.entity.Permission;
import cn.qiyu5522.tk_ems.entity.Role;
import cn.qiyu5522.tk_ems.mapper.PermissionMapper;
import cn.qiyu5522.tk_ems.mapper.RoleMapper;
import cn.qiyu5522.tk_ems.mapper.UserRoleMapper;
import cn.qiyu5522.tk_ems.service.RoleService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: tk_ems
 * @Package: cn.qiyu5522.tk_ems.stpinterface
 * @ClassName: StpInterfaceImpl
 * @Author: [Toneky]
 * @Date: 2023/2/22 16:18
 * @Version: V1.0
 **/
/**
 * 自定义权限验证接口扩展
 */
@Component    // 保证此类被SpringBoot扫描，完成Sa-Token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleService roleService;

    // 用户角色关联表
    @Resource
    private UserRoleMapper userRoleMapper;
    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String logInfo = (String) loginId;
        Long userId = Long.valueOf(logInfo.split("-")[0]);
        // 查询用户拥有的角色
        List<Role> roles = roleService.listRolesByUserId(userId);
        if(roles.size()==0){
            return new ArrayList<>(0);
        }
        // 根据角色查询权限
        List<Permission> permissions = new ArrayList<>();
        List<String> list = new ArrayList<String>();
        String role_permissions = "";
        for (Role role : roles) {
            permissions = roleService.listPermissionsByRoleId(role.getId());
            if(permissions.size()!=0){
                permissions = permissions.stream()
                        .map(permission -> permission.setName(role.getName() + "." + permission.getName()))
                        .collect(Collectors.toList());
            }
        }
        list.addAll(permissions.stream().map(Permission::getName).collect(Collectors.toList()));
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String logInfo = (String) loginId;
        Long userId = Long.valueOf(logInfo.split("-")[0]);
        List<Role> roles = roleService.listRolesByUserId(userId);
        if(roles.size()==0){
            return new ArrayList<>(0);
        }
        // 实际项目中要根据具体业务逻辑来查询角色
        List<String> list = new ArrayList<String>();
        for (Role role : roles) {
            list.add(role.getName());
        }
        return list;
    }
}
